﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using Bookvar.ObjectModel;
using Bookvar.UI.Commands;
using Bookvar.UI.DragDrop;
using Bookvar.UI.ViewModel;
using Bookvar.UI.ViewModel.LiveImages;
using Bookvar.Web;
using LocalizationResources = Bookvar.UI.Localization.Resources;

namespace BookvarWpf.Windows
{
    /// <summary>
    /// Interaction logic for LiveImagesWindow.xaml
    /// </summary>
    public partial class LiveImagesWindow : BookvarToolWindow
    {
        private readonly DispatcherTimer timer;
        private Thread workerThread;

        #region SearchTerm

        public static readonly DependencyProperty SearchTermProperty =
            DependencyProperty.Register( "SearchTerm", typeof ( string ), typeof ( LiveImagesWindow ),
                                         new FrameworkPropertyMetadata( default( string ), OnSearchTermChanged ) );

        public string SearchTerm
        {
            get { return (string) GetValue( SearchTermProperty ); }
            set { SetValue( SearchTermProperty, value ); }
        }

        #endregion

        public LiveImagesWindow()
        {
            InitializeComponent();
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds( 1 );
            timer.Tick += delegate
                              {
                                  timer.Stop();
                                  SearchTerm = txtSearch.Text;
                              };

            txtSearch.TextChanged += delegate
                                         {
                                             timer.Stop();
                                             timer.Start();
                                         };
            DragDropManager.SetDragSourceAdvisor( imagesItemsControl, new ImageViewerDragSourceAdvisor() );

            var viewModel = new LiveImagesViewModel();
            ViewModelBase.AddCommandAndInputBindings( this, viewModel );
        }

        protected virtual void OnSearchStart()
        {
            progressAnimation.Start();
        }

        protected virtual void OnSearchStop()
        {
            progressAnimation.Stop();
        }

        private static void OnSearchTermChanged( DependencyObject element, DependencyPropertyChangedEventArgs e )
        {
            var window = (LiveImagesWindow) element;
            var searchTerm = e.NewValue as string;
            if ( !string.IsNullOrEmpty( searchTerm ) )
            {
                window.OnSearchStart();
                // Start worker thread to access internet, get search result
                window.workerThread = new Thread( window.ExecuteImageSearch );
                window.workerThread.Start( searchTerm );
            }
        }

        private void PopulateImages( IEnumerable<ImageInfo> images )
        {
            OnSearchStop();
            imagesItemsControl.Items.Clear();
            foreach ( ImageInfo info in images )
            {
                imagesItemsControl.Items.Add( info );
            }
        }

        private void ExecuteImageSearch( object searchTerm )
        {
            IEnumerable<ImageInfo> images = LiveService.GetImages( (string) searchTerm, 20 );
            imagesItemsControl.Dispatcher.BeginInvoke( DispatcherPriority.DataBind, new SearchDelegate( PopulateImages ),
                                                       images );
        }

        private void Image_PreviewMouseDown( object sender, MouseButtonEventArgs e )
        {
            if ( e.ClickCount == 2 )
            {
                var image = (Image) sender;
                var imageInfo = (ImageInfo) image.DataContext;
                var parameter = new LiveImageInfo( imageInfo, image.Source,
                                                   new Size( image.ActualWidth, image.ActualHeight ) );
                BookvarCommands.AddImage.Execute( parameter, this );
            }
        }

        #region Nested type: SearchDelegate

        private delegate void SearchDelegate( IEnumerable<ImageInfo> images );

        #endregion
    }
}